package com.dodayum.java8.thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolUtil {

    ThreadPoolExecutor threadPoolExecutor;

    public ThreadPoolExecutor getThreadPoolExecutor() {
        return threadPoolExecutor;
    }

    public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) {
        this.threadPoolExecutor = threadPoolExecutor;
    }

    public ThreadPoolUtil(){
        threadPoolExecutor =  new ThreadPoolExecutor(
                5,// 最小线程数
                10, // 最大线程数
                200, // 线程池存活时间
                TimeUnit.MILLISECONDS, //线程池存活时间单位
                new ArrayBlockingQueue<>(5),// 队列
                threadFactory,// 线程池工厂
                rejectedExecutionHandler// 拒绝策略
        );
    }


    static ThreadFactory threadFactory = new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            int index = new AtomicInteger().incrementAndGet();
            return new Thread(r, "当前线程id:Thread-" + index);
        }
    };
    static RejectedExecutionHandler rejectedExecutionHandler = new RejectedExecutionHandler() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            int corePoolSize = executor.getCorePoolSize();
            int maximumPoolSize = executor.getMaximumPoolSize();
            System.out.println("当前线程数：" + corePoolSize + ",最大线程数：" + maximumPoolSize);
        }
    };

}
